package com.pqc.tbk.web.scheduling;

import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;

import com.pqc.tbk.utils.MSGSender;
import com.pqc.tbk.utils.MailSender;

/**
 * 短信剩余数量监听器
 * 
 * @author long, create on 2012-8-8 下午7:47:32
 * 
 */
public class MessageJob implements ServletContextListener {

	private Timer timer = null;
	private static Logger logger = org.slf4j.LoggerFactory
			.getLogger(MessageJob.class);
	private final String MSG_NUM_WARN = "短信数量不足,还剩条数为:";

	@Override
	public void contextInitialized(final ServletContextEvent sce) {
		logger.info("查询短信剩余数量");
		final long period = 24 * 60 * 60 * 1000L;
		final long delay = period
				- ((System.currentTimeMillis() + (22 * 60 * 60 * 1000L)) % period);
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					final Integer restNum = Integer.parseInt(MSGSender
							.restNum());
					if (restNum < 20) {
						MailSender.send(MailSender.ACCEPT_MSG_ADDRESS,
								MSG_NUM_WARN, MSG_NUM_WARN + restNum);
					}
				}
				catch (final Exception e) {
					e.printStackTrace();
				}
			}
		}, delay, period);
	}

	@Override
	public void contextDestroyed(final ServletContextEvent sce) {
		if (timer != null) {
			timer.cancel();
		}
		logger.info("结束任务");
	}

}
